<template>
  <BasicModal v-bind="$attrs" @register="registerAnswerModal" title="消息回复" @ok="handleSubmit" :width="800" destroyOnClose>
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script setup lang="ts">
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { ref, unref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { saveReply } from '../JhFeedback.api';

  // Emits声明
  const emit = defineEmits(['register', 'success']);
  const isUpdate = ref(true);
  const isDetail = ref(false);
  //表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate, scrollToField }] = useForm({
    labelWidth: 150,
    schemas: [
      {
        label: '评价内容',
        field: 'feedbackContent',
        component: 'InputTextArea',
        componentProps: {
          disabled: true,
          rows: 4,
        },
        colProps: { span: 24 },
      },
      {
        label: '回复内容',
        field: 'text',
        component: 'InputTextArea',
        componentProps: {
          placeholder: '请输入回复内容',
          rows: 4,
        },
        required: true,
        colProps: { span: 24 },
      },
      {
        label: '',
        field: 'id',
        component: 'Input',
        show: false,
      },
    ],
    showActionButtonGroup: false,
    baseColProps: { span: 24 },
  });

  //表单赋值
  const [registerAnswerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await resetFields();
    setModalProps({ confirmLoading: false, showCancelBtn: true, showOkBtn: true });
    isUpdate.value = !!data?.isUpdate;
    isDetail.value = false; // 回复模态框始终是编辑状态
    if (unref(isUpdate)) {
      //表单赋值
      await setFieldsValue({
        ...data.record,
      });
    }
    //回复内容始终可编辑
    setProps({ disabled: false });
  });

  //表单提交事件
  // 在handleSubmit函数中
  async function handleSubmit() {
    try {
      let values = await validate();
      setModalProps({ confirmLoading: true });
      // 确保values中包含id
      if (!values.id && data && data.record && data.record.id) {
        values.id = data.record.id;
      }
      //提交表单
      await saveReply(values);
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>

<style scoped lang="less">
  /** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-calendar-picker) {
    width: 100%;
  }
</style>
